package com.base.common.utils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.WordUtils;

/**
 * String 工具类 2013-12-4 上午11:25:44
 *
 * @author jay.zhoujingjie
 */
public class StringUtils {
	/**
	 * 是否为空
	 *
	 * @param str
	 * @return boolean
	 * @author jay.zhoujingjie
	 */
	public static boolean isEmpty(String str) {
		if (str == null || str.length() < 1) {
			return true;
		}
		return false;
	}

	/**
	 * 是否不为空
	 *
	 * @param str
	 * @return boolean
	 * @author jay.zhoujingjie
	 */
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 去掉空格后是否为空
	 *
	 * @param str
	 * @return boolean
	 * @author jay.zhoujingjie
	 */
	public static boolean isEmptyByTrim(String str) {
		if (str == null || str.trim().length() < 1) {
			return true;
		}
		return false;
	}

	/**
	 * 去掉空格后是否不为空
	 *
	 * @param str
	 * @return boolean
	 * @author jay.zhoujingjie
	 */
	public static boolean isNotEmptyByTrim(String str) {
		return !isEmptyByTrim(str);
	}

	/**
	 * 首字母大写
	 *
	 * @param str
	 * @return String
	 * @author jay.zhoujingjie
	 */
	public String capitalize(String str) {
		return org.apache.commons.lang3.StringUtils.capitalize(str);
	}

	/**
	 * 计算字符串出现的个数
	 *
	 * @param str
	 * @param sub
	 * @return Integer
	 * @author jay.zhoujingjie
	 */
	public static Integer countMatches(String str, String sub) {
		return org.apache.commons.lang3.StringUtils.countMatches(str, sub);
	}

	/**
	 * 转换大小写
	 *
	 * @param str
	 * @return String
	 * @author jay.zhoujingjie
	 */
	public static String swapCase(String str) {
		return WordUtils.swapCase(str);
	}

	/**
	 * 字符串解析，防XSS注入
	 *
	 * @param str
	 * @return String
	 * @author jay.zhoujingjie
	 */
	public static String encodeHTML(String str) {
		/*
		 * return org.apache.commons.lang3.StringUtils.replaceEach(str, new
		 * String[]{"&", "<", ">", "\"", "'", "/"}, new String[]{"&amp;",
		 * "&lt;", "&gt;", "&quot;", "&#x27;", "&#x2F;"} );
		 */
		return StringEscapeUtils.escapeXml(str);
	}

	/**
	 * 字符串过滤
	 *
	 * @param str
	 * @return
	 */
	public static String filter(String str) {
		if (str == null) {
			return null;
		}
		char[] content = new char[str.length()];
		str.getChars(0, str.length(), content, 0);
		StringBuilder result = new StringBuilder(50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '>':
				result.append("&gt;");
				break;
			case '<':
				result.append("&lt;");
				break;
			case '\"':
				result.append("&quot;");
				break;
			case '\'':
				result.append("&acute;");
			default:
				result.append(content[i]);
			}
		}
		return result.toString();
	}
}
